package drds.binlog.parse.inbound.mysql;

import com.lmax.disruptor.LifecycleAware;
import com.lmax.disruptor.WorkHandler;
import drds.binlog.LogEvent;
import drds.binlog.event.RowsLogEvent;
import drds.binlog.parse.exception.BinlogParseException;
import drds.binlog.protocol.entry_protocol_proto.Entry;


class DmlParserStage implements WorkHandler<MessageEvent>, LifecycleAware
{

    private MultiStageCoprocessor mysqlMultiStageCoprocessor;

    public DmlParserStage(MultiStageCoprocessor mysqlMultiStageCoprocessor)
    {
        this.mysqlMultiStageCoprocessor = mysqlMultiStageCoprocessor;
    }

    @Override
    public void onEvent(MessageEvent messageEvent) throws Exception
    {
        try
        {
            if (messageEvent.isNeedDmlParse())
            {
                int eventType = messageEvent.getLogEvent().getLogHeader().getType();
                Entry entry = null;
                switch (eventType)
                {
                    case LogEvent.ROWS_QUERY_LOG_EVENT:
                        entry = mysqlMultiStageCoprocessor.logEventConvert.parse(messageEvent.getLogEvent(), false);
                        break;
                    default:
                        // 单独解析dml事件
                        entry = mysqlMultiStageCoprocessor.logEventConvert.parseRowsEvent((RowsLogEvent) messageEvent.getLogEvent(), messageEvent.getTableMetaData());
                }

                messageEvent.setEntry(entry);
            }
        } catch (Throwable e)
        {
            mysqlMultiStageCoprocessor.binlogParseException = new BinlogParseException(e);
            throw mysqlMultiStageCoprocessor.binlogParseException;
        }
    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onShutdown()
    {

    }
}
